package com.android.example.app3;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.media.Image;
import android.os.Build;

import androidx.annotation.RequiresApi;

import java.nio.ByteBuffer;

public class ImageToBitmapUtils {

    /**
     * 将 Image 对象转换为 Bitmap 对象
     *
     * @param image           要转换的 Image 对象
     * @param rotationDegrees 图像的旋转角度
     * @return 转换后的 Bitmap 对象
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static Bitmap imageToBitmap(Image image, int rotationDegrees) {
        if (image.getFormat() == ImageFormat.YUV_420_888) {
            ByteBuffer buffer = image.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.capacity()];
            buffer.get(bytes);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
            if (bitmap != null) {
                return rotateBitmap(bitmap, rotationDegrees);
            }
        } else if (image.getFormat() == ImageFormat.JPEG) {
            ByteBuffer buffer = image.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.capacity()];
            buffer.get(bytes);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            if (bitmap != null) {
                return rotateBitmap(bitmap, rotationDegrees);
            }
        }
        return null;
    }

    /**
     * 旋转 Bitmap 对象
     *
     * @param bitmap  要旋转的 Bitmap 对象
     * @param degrees 旋转的角度
     * @return 旋转后的 Bitmap 对象
     */
    private static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
        if (degrees != 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(degrees);
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        return bitmap;
    }
}